#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>

//UDP client
#define IP  "127.0.0.1"
#define SPORT 60000
#define SIZE  100

int main()
{
	int socketID = 0;
	char buf[SIZE] = {0};
	int addrLength = 0;
	struct sockaddr_in addr;
	ssize_t ret = 0;
	
	//创建socket 
	socketID = socket( PF_INET, SOCK_DGRAM, 0 );
	if ( 0 > socketID )
	{
		perror("socket error");
		return -1;
	}
	printf("client socket ok\r\n");
	
	//准备要发送的消息
	fgets(buf, SIZE - 1, stdin);
	//设置对方的地址
	addrLength = sizeof(addr);
	memset(&addr, 0, addrLength);
	addr.sin_family = PF_INET;
	addr.sin_port = htons(SPORT);
	addr.sin_addr.s_addr = inet_addr(IP);
	//发送消息
	ret = sendto( socketID, buf, strlen(buf), 0, (struct sockaddr *)&addr, addrLength);
	if ( 0 > ret )
	{
		perror("send to error");
	}
	memset(buf, SIZE, 0);
	//等待对方的回应
	ret = recvfrom(socketID, buf, SIZE - 1, 0, (struct sockaddr *)&addr, &addrLength);
	if ( 0 > ret )
	{
		perror("recvfrom error");
	}
	else 
	{
		//处理消息
		printf("client get data:%s, from port:%d\r\n", buf, ntohs(addr.sin_port));
	}
	
	//关闭socket
	close(socketID);
	return 0;
}
